#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys
import cgi
import json
import db_conf

con = None

try:
    qform = cgi.FieldStorage()
    de_reagent = qform.getvalue('search_input')	
    config = db_conf.getConfig('metabvis.conf')
    con = psycopg2.connect(host=db_conf.getDBHost(config), database=db_conf.getDBName(config), port=db_conf.getDBPort(config), user=db_conf.getUser(config), password=db_conf.getPassword(config)) 
    cur = con.cursor()
    
    if (de_reagent == None):# or de_reagent == "MSTFA"):
        de_reagent = "%TMS%"
    else:
        de_reagent = "%" + de_reagent + "%"
    select_s = "select compound_id, compound_name, sum_formula from compound c where c.compound_name like '" + de_reagent + "' and c.compound_id not in (select product_compound from compound_derivatization) order by c.time_lastmod desc"
    cur.execute(select_s)          
    rows = cur.fetchall()    
    print "Content-type: text/html;charset=utf-8\r\n"
    pa = {}
    plist = []
    for row in rows:
	pi = {}
        pi["id"] = row[0]
        pi["prod"] = row[1]
        pi["form"] = row[2]
	pa[row[1]] = row[0]
        plist.append(pi)
    outjs = {"orphan_products":plist}#, "cnames_hash":pa} 
    print json.dumps(outjs)
    #print len(plist)
except psycopg2.DatabaseError, e:
    print 'Error %s' % e    
    sys.exit(1)    
finally:
    if con:
        con.close()
